<template>
  <view>
    <p>系统设置</p>
  </view>
</template>

<script>
export default {
  name: "system",
  created() {
    this.startConnect();
  },
  onLaunch() {},
  data() {
    return {
      deviceId: "",
      serviceId: "",
      connectedDeviceId: "",
      notifyServicweId: "",
      notifyCharacteristicsId: "",
      deviceName: "LAPTOP-U6C7G2RG",
      services: "",
      failTimes: 0,
    };
  },
  methods: {
    startConnect() {
      const that = this;
      uni.showToast({
        icon: "none",
        title: "开启蓝牙适配",
        duration: 1500,
      });
      wx.getSetting({
        success(res) {
          if (!res.authSetting["scope.bluetooth"]) {
            wx.authorize({
              scope: "scope.bluetooth",
              success() {
                // 1. 初始化蓝牙设备
                wx.openBluetoothAdapter({
                  success: function (res) {
                    console.log("初始化蓝牙适配器");
                    console.log(res);
                    setTimeout(() => {
                      that.getBluetoothAdapterState();
                    }, 1000);
                  },
                  fail: function (err) {
                    console.log(err);
                    wx.showToast({
                      title: "蓝牙初始化失败",
                      icon: "success",
                      duration: 2000,
                    });
                  },
                });
              },
              fail(err) {
                console.log(err);
              },
            });
          } else {
            // 1. 初始化蓝牙设备
            wx.openBluetoothAdapter({
              success: function (res) {
                console.log("初始化蓝牙适配器");
                console.log(res);
                setTimeout(() => {
                  that.getBluetoothAdapterState();
                }, 1000);
              },
              fail: function (err) {
                console.log(err);
                wx.showToast({
                  title: "蓝牙初始化失败",
                  icon: "success",
                  duration: 2000,
                });
              },
            });
          }
        },
      });

      // wx.onBluetoothAdapterStateChange(function (res) {
      //   var available = res.available;
      //   if (available) {
      //     that.startBluetoothDevicesDiscovery();
      //   }
      // });
      // setTimeout(function () {
      //   wx.hideLoading();
      //   console.log("hideLoading");
      // }, 1000);
    },
    // 2. 检测本机蓝牙是否可用
    getBluetoothAdapterState() {
      const that = this;
      wx.getBluetoothAdapterState({
        success(res) {
          if (res.available) {
            that.startBluetoothDevicesDiscovery();
            // if (res.discovering) {
            //   that.onBluetoothDeviceFound();
            // } else {
            //   that.startBluetoothDevicesDiscovery();
            // }
          }
        },
      });
    },
    // 3. 开始搜索蓝牙设备
    startBluetoothDevicesDiscovery() {
      var that = this;
      uni.showToast({
        icon: "none",
        title: "蓝牙搜索",
        duration: 1500,
      });
      setTimeout(() => {
        wx.startBluetoothDevicesDiscovery({
          // services: [],
          // interval: 0,
          // allowDuplicatesKey: false,
          success: function (res) {
            console.log(res);
            that.getBluetoothDevices();
          },
          fail: function (err) {
            console.log(err);
          },
        });
      }, 1000);
    },
    onBluetoothDeviceFound() {
      let that = this;
      wx.onBluetoothDeviceFound((res) => {
        res.devices.forEach((device) => {
          if (!device.name && !device.localName) {
            //将没有名字的设备命名为了“未知设备”
            device.name = "未知设备";
            // return
          }
          const foundDevices = that.data.devices;
          //console.log(foundDevices)
          const idx = that.inArray(foundDevices, "deviceId", device.deviceId);
          const data = {};
          if (idx === -1) {
            //新设备，直接存起来
            data[`devices[${foundDevices.length}]`] = device;
          } else {
            //老设备覆盖一遍
            data[`devices[${idx}]`] = device;
          }
          // console.log(data)
          that.setData(data);
        });
      });
    },
    // 4. 获取搜索到的蓝牙设备列表
    getBluetoothDevices() {
      var that = this;
      setTimeout(() => {
        wx.getBluetoothDevices({
          success: function (res) {
            // wx.onBluetoothDeviceFound(function (res) {
            //   var devices = res.devices;
            //   console.log(res);
            //   console.log("new device list has founded");
            //   // console.dir(devices);
            //   // console.log(ab2hex(devices[0].advertisData));
            // });
            console.log(res);
            if (res.devices.length > 0) {
              // if (JSON.stringify(res.devices).indexOf(that.deviceName) !== -1) {
              //   for (let i = 0; i < res.devices.length; i++) {
              //     if (that.deviceName === res.devices[i].name) {
              //       /* 根据指定的蓝牙设备名称匹配到deviceId */
              //       that.deviceId = that.devices[i].deviceId;
              //       setTimeout(() => {
              //         that.connectTO();
              //       }, 2000);
              //     }
              //   }
              // }
              // if (JSON.stringify(res.devices).indexOf(that.deviceName) !== -1) {
              //   for (let i = 0; i < res.devices.length; i++) {
              //     if (
              //       that.deviceName === res.devices[i].name ||
              //       res.devices[i].name == "未知设备"
              //     ) {
              //       /* 根据指定的蓝牙设备名称匹配到deviceId */
              //       that.deviceId = res.devices[i].deviceId;
              //       console.log(that.deviceId);
              //       setTimeout(() => {
              //         that.connectTO();
              //       }, 2000);
              //     }
              //   }
              // }
              for (let i = 0; i < res.devices.length; i++) {
                if (
                  that.deviceName === res.devices[i].name ||
                  res.devices[i].name == "未知设备"
                ) {
                  /* 根据指定的蓝牙设备名称匹配到deviceId */
                  that.deviceId = res.devices[i].deviceId;
                  console.log(that.deviceId);
                  setTimeout(() => {
                    that.connectTO();
                  }, 2000);
                }
              }
            }
          },
          fail(res) {
            console.log(res, "获取蓝牙设备列表失败=====");
          },
        });
      }, 2000);
    },
    // 5. 连接蓝牙
    connectTO() {
      const that = this;
      wx.createBLEConnection({
        deviceId: that.deviceId,
        timeout: 1000 * 20,
        success: function (res) {
          console.log(res);
          that.connectedDeviceId = that.deviceId;
          /* 6.获取连接设备的service服务 */
          that.getBLEDeviceServices();
          wx.stopBluetoothDevicesDiscovery({
            success: function (res) {
              console.log(res, "停止搜索");
            },
            fail(err) {
              console.log(err);
            },
          });
        },
        fail: function (err) {
          console.log(err);
          if (that.failTimes < 5) {
            that.failTimes++;
            wx.stopBluetoothDevicesDiscovery({
              success: function (res) {
                console.log(res, "停止搜索");
              },
              fail(err) {
                console.log(err);
              },
            });
            wx.closeBluetoothAdapter();
            wx.closeBLEConnection({
              deviceId: that.deviceId,
              success: (res) => {
                console.log(res);
              },
            });
            that.startConnect();
            // that.getBLEDeviceServices();
            // that.getBluetoothDevices();
          }
        },
      });
    },
    // 6.获取连接设备的service服务
    getBLEDeviceServices() {
      const that = this;
      setTimeout(() => {
        wx.getBLEDeviceServices({
          deviceId: that.connectedDeviceId,
          success: function (res) {
            console.log(res);
            that.services = res.services;
            console.log(that.services);
            /* 获取连接设备的所有特征值 */
            that.getBLEDeviceCharacteristics();
          },
          fail: (err) => {
            console.log(err);
          },
        });
      }, 2000);
    },
    // 7. 获取蓝牙设备特征值
    getBLEDeviceCharacteristics() {
      const that = this;
      setTimeout(() => {
        wx.getBLEDeviceCharacteristics({
          deviceId: that.connectedDeviceId,
          serviceId: that.services[2].uuid,
          success: function (res) {
            console.log(res);
            for (var i = 0; i < res.characteristics.length; i++) {
              if (
                (res.characteristics[i].properties.notify ||
                  res.characteristics[i].properties.indicate) &&
                res.characteristics[i].properties.read &&
                res.characteristics[i].properties.write
              ) {
                console.log(
                  res.characteristics[i].uuid,
                  "蓝牙特征值 =========="
                );
                /* 获取蓝牙特征值 */
                that.notifyCharacteristicsId = res.characteristics[i].uuid;
                // 启用低功耗蓝牙设备特征值变化时的 notify 功能
                that.notifyBLECharacteristicValueChange();
              }
            }
          },
          fail: function (res) {},
        });
      }, 1000);
    },

    // 8. 启动notify 蓝牙监听功能 然后使用 wx.onBLECharacteristicValueChange用来监听蓝牙设备传递数据
    notifyBLECharacteristicValueChange() {
      // 启用低功耗蓝牙设备特征值变化时的 notify 功能
      const that = this;
      console.log("6.启用低功耗蓝牙设备特征值变化时的 notify 功能");
      wx.notifyBLECharacteristicValueChange({
        state: true,
        deviceId: that.connectedDeviceId,
        serviceId: that.notifyServicweId,
        characteristicId: that.notifyCharacteristicsId,
        complete(res) {
          /*用来监听手机蓝牙设备的数据变化*/
          wx.onBLECharacteristicValueChange(function (res) {
            /**/
            that.balanceData += that.buf2string(res.value);
            that.hexstr += that.receiveData(res.value);
          });
        },
        fail(res) {
          console.log(res, "启用低功耗蓝牙设备监听失败");
          that.measuringTip(res);
        },
      });
    },

    /*转换成需要的格式*/
    buf2string(buffer) {
      var arr = Array.prototype.map.call(new Uint8Array(buffer), (x) => x);
      return arr
        .map((char, i) => {
          return String.fromCharCode(char);
        })
        .join("");
    },
    receiveData(buf) {
      return this.hexCharCodeToStr(this.ab2hex(buf));
    },

    /*转成二进制*/
    ab2hex(buffer) {
      var hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
          return ("00" + bit.toString(16)).slice(-2);
        }
      );
      return hexArr.join("");
    },

    /*转成可展会的文字*/
    hexCharCodeToStr(hexCharCodeStr) {
      var trimedStr = hexCharCodeStr.trim();
      var rawStr =
        trimedStr.substr(0, 2).toLowerCase() === "0x"
          ? trimedStr.substr(2)
          : trimedStr;
      var len = rawStr.length;
      var curCharCode;
      var resultStr = [];
      for (var i = 0; i < len; i = i + 2) {
        curCharCode = parseInt(rawStr.substr(i, 2), 16);
        resultStr.push(String.fromCharCode(curCharCode));
      }
      return resultStr.join("");
    },

    // 9. 向蓝牙设备发送数据
    sendData(str) {
      let that = this;
      let dataBuffer = new ArrayBuffer(str.length);
      let dataView = new DataView(dataBuffer);
      for (var i = 0; i < str.length; i++) {
        dataView.setUint8(i, str.charAt(i).charCodeAt());
      }
      let dataHex = that.ab2hex(dataBuffer);
      this.writeDatas = that.hexCharCodeToStr(dataHex);
      wx.writeBLECharacteristicValue({
        deviceId: that.connectedDeviceId,
        serviceId: that.notifyServicweId,
        characteristicId: that.notifyCharacteristicsId,
        value: dataBuffer,
        success: function (res) {
          console.log("发送的数据：" + that.writeDatas);
          console.log("message发送成功");
        },
        fail: function (err) {
          console.log(err);
        },
        complete: function (res) {},
      });
    },

    // 断开设备连接
    closeConnect() {
      if (that.connectedDeviceId) {
        wx.closeBLEConnection({
          deviceId: that.connectedDeviceId,
          success: function (res) {
            that.closeBluetoothAdapter();
          },
          fail(res) {},
        });
      } else {
        that.closeBluetoothAdapter();
      }
    },

    // 关闭蓝牙模块
    closeBluetoothAdapter() {
      wx.closeBluetoothAdapter({
        success: function (res) {
          console.log("关闭蓝牙模块");
        },
        fail: function (err) {
          console.log(err);
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
</style>